package com.runvp.handler;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.constant.ConstantRedisKey;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.core.redis.RedisLockClient;
import com.runvp.common.enums.NettyCmd;
import com.runvp.common.enums.NettyType;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.common.util.ToolUtils;
import com.runvp.service.tcp.TcpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class CmdReportHandler {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisLockClient lockClient;
    @Autowired
    private TcpService tcpService;
    /**
     * 设备上报基本信息
     * @param parseBody
     * @return MessageResBody
     */
    public MessageResBody handle(MessageReceiveBody parseBody){
        log.info("设备上报基本信息处理:::receiveBody:{}",JSONObject.toJSONString(parseBody));
        String batchNo = System.nanoTime()+"";
        String sn = parseBody.getTerminalId();
        long id = ToolUtils.objTOLong(tcpService.instanceRedisUtil().getCacheObject(ConstantRedisKey.DEVICE_SN_ID+sn));
        tcpService.addBizTcpRecord(parseBody.setBatchNo(batchNo));
        MessageResBody resBody = buildRes(id);
        resBody.setDeviceId(id);
        resBody.setTerminalId(sn);
        tcpService.addBizTcpRecord(resBody.setBatchNo(batchNo));
        log.info("设备上报基本信息处理:::resBody:{}",JSONObject.toJSONString(resBody));
        return resBody;
    }
    /**
     * 结构结果体
     * @return str
     */
    private JSONObject buildBody(Long id){
        JSONObject map = new JSONObject();
        map.put("id",id);
        return map;
    }


    /**
     * 默认报文
     *
     * @return MessageResBody
     */
    public MessageResBody buildRes(Long id) {
        MessageResBody resBody = new MessageResBody(NettyType.SERVER_RECEIVE_DEVICE.getCode(), NettyCmd.SERVER_RES_BASE_INFO.getCode());
        resBody.setDid("000000000000");
        resBody.setVersion("01");
        resBody.setBodyJson(buildBody(id)).buildRes();
        log.info("服务器组装回应设备上报基本信息报文完毕");
        return resBody;
    }
}
